import React from 'react';

import {
  View,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
} from 'react-native';

import {Button} from 'react-native-elements';
import dismissKeyboard from 'dismissKeyboard';

import Config from '../../config';
import BasePage from '../common/BasePage';
import Constants from '../../common/Constants';
import SizeUtils from '../../common/SizeUtils';
import CommonStyles from '../../common/CommonStyles';
import ResponseConstants from '../../common/ResponseConstants';

import RequestSmsAction from '../../actions/login/RequestSmsAction';
import LoginSendRegisteAction from '../../actions/login/LoginSendRegisteAction';

export default class LoginRegistePage extends BasePage {
  constructor(props) {
    super(props);

    this.state.viewStatus = 1;
    this.state.phoneNum = "";
    this.state.smsNum = "";
    this.state.password = "";
    this.state.nickName = "";
    this.state.authorization = "0";
    this.state.smsIntervalTick = -1;
    this.state.eyeOpened = false;

    this._width = SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(54 * 2);
  }

  shouldComponentUpdate(nextProps, nextState) {
    this._checkGetAutorizationInShouldUpdate(nextProps, nextState);
    if (this.state.viewStatus != nextState.viewStatus) {
      if(nextState.viewStatus == ResponseConstants.status_sms_success) {
        this._smsInterval = setInterval(this._updateInterval.bind(this), 1000);
        this._updateInterval();
      }
      else if(nextState.viewStatus == 1){
        this._clearInterval();
      }
    }
    return true;
  }

  _dealLeavePage() {

  }

  _updateInterval() {
    var tick = this.state.smsIntervalTick == -1 ? 60 : this.state.smsIntervalTick - 1;
    if(tick == 0) {
      this._clearInterval();
      tick = -1;
    }
    this.setState({
      smsIntervalTick: tick,
    });
  }

  _clearInterval() {
    if(this._smsInterval) {
      clearInterval(this._smsInterval);
      this._smsInterval = null;
    }
  }

  render() {
    return(
      <TouchableOpacity style={{paddingTop:Config.paddingTop,
          flex:1,
          backgroundColor:"#ffffffff",
          paddingLeft:SizeUtils.translateDesignWidthToCode(54),
          paddingRight:SizeUtils.translateDesignWidthToCode(54),
         flexDirection:"column", alignItems:"center",
       }} onPress={() => dismissKeyboard()} activeOpacity={1}>
         {this._renderWelcomeImage()}
         {this._renderNameText()}
         {this._renderPhoneText()}
         {this._renderPasswordText()}
         {this._renderSmsText()}
         {this._renderLoginButton()}
         {this._renderNavigationBar()}
         {this._renderProvision()}
      </TouchableOpacity>
    )
  }

  _renderWelcomeImage() {
    return(
      <View style={{width:this._width, height:SizeUtils.translateDesignWidthToCode(135),
          marginTop:SizeUtils.translateDesignHeightToCode(74),
          flexDirection:"row",
          justifyContent:"center"}}>
        <Image source={require("../../../resource/images/login/welcome.png")}
          style={{width:SizeUtils.translateDesignWidthToCode(400),
            height:SizeUtils.translateDesignWidthToCode(135)}}/>
      </View>
    )
  }

  _renderProvision() {
    return (
      <TouchableOpacity style={{flexDirection:"row", justifyContent:"center", position:"absolute",
          bottom:SizeUtils.translateDesignHeightToCode(30)}} onPress={this._onPressProvision.bind(this)}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30), color:"#666666"}}>
          注册即表示同意本APP
        </Text>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30), color:"#db3132"}}>
          注册服务条款
        </Text>
      </TouchableOpacity>
    )
  }

  _onPressProvision() {
    this.gotoPage(Config.pages.login_provision);
  }

  _onPhoneNumberChange(text) {
      let newText = '';
      let numbers = '0123456789';

      for (var i = 0; i < text.length; i++) {
          if ( numbers.indexOf(text[i]) > -1 ) {
              newText = newText + text[i];
          }
      }
      this.setState({phoneNum: newText})
  }

  _onSmsNumChange(text) {
      let newText = '';
      let numbers = '0123456789';

      for (var i = 0; i < text.length; i++) {
          if ( numbers.indexOf(text[i]) > -1 ) {
              newText = newText + text[i];
          }
      }
      this.setState({smsNum: newText})
  }

  _onNameChange(text) {
      let newText = '';
      // 只能输入英文、数字、汉字
      const reg = new RegExp(/([^A-Za-z0-9\u4E00-\u9FA5])/g)
      text = '' + text;
      newText = text.replace(reg,'')
      this.setState({nickName: newText})
  }

  _renderNameText() {
    return (
      <View style={{
            height:SizeUtils.translateDesignHeightToCode(94),
            borderBottomWidth:SizeUtils.translateFontSizeToCode(3),
            borderColor:"#eeeeee",
            marginTop:SizeUtils.translateDesignHeightToCode(60),
          }}>
        <TextInput
          style={{
            padding:0,
            width:this._width,
            height:SizeUtils.translateDesignHeightToCode(94),
            borderWidth: 0,
            textAlignVertical: "center",
            fontSize:SizeUtils.translateFontSizeToCode(32),}}
          onChangeText = {(text) => this._onNameChange(text)}
          placeholder = "昵称(4-20字符)"
          multiline = {false}
          underlineColorAndroid="transparent"
          maxLength = {20}
          value = {this.state.nickName}
        />
      </View>
    )
  }

  _renderPhoneText() {
    return (
      <View style={{
            height:SizeUtils.translateDesignHeightToCode(94),
            borderBottomWidth:SizeUtils.translateFontSizeToCode(3),
            borderColor:"#eeeeee",
            // marginTop:SizeUtils.translateDesignHeightToCode(72),
          }}>
        <TextInput
          style={{
            padding:0,
            width:this._width,
            height:SizeUtils.translateDesignHeightToCode(94),
            borderWidth: 0,
            textAlignVertical: "center",
            fontSize:SizeUtils.translateFontSizeToCode(32),}}
          onChangeText = {(text) => this._onPhoneNumberChange(text)}
          placeholder = "手机号"
          multiline = {false}
          maxLength={11}
          underlineColorAndroid="transparent"
          keyboardType="numeric"
          keyboardAppearance="dark"
          value = {this.state.phoneNum}
        />
      </View>
    )
  }

  _renderPasswordText() {
    return (
      <View style={{
            width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(54 * 2),
            height:SizeUtils.translateDesignHeightToCode(94),
            borderBottomWidth:SizeUtils.translateFontSizeToCode(3),
            borderColor:"#eeeeee",
            // marginTop:SizeUtils.translateDesignHeightToCode(74),
            flexDirection:"row", justifyContent:"space-between",
          }}>
        <TextInput
          style={{
            padding:0,
            width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(54 * 2 + 100),
            height:SizeUtils.translateDesignHeightToCode(94),
            borderWidth: 0,
            textAlignVertical: "center",
            fontSize:SizeUtils.translateFontSizeToCode(32),}}
          onChangeText = {(password) => this.setState({password})}
          placeholder = "请输入密码(6-16位)"
          multiline = {false}
          maxLength={16}
          underlineColorAndroid="transparent"
          value = {this.state.password}
          secureTextEntry = {!this.state.eyeOpened}
        />
        <TouchableOpacity style={{width:SizeUtils.translateDesignWidthToCode(100),
          height:SizeUtils.translateDesignWidthToCode(94), justifyContent:"center", alignItems:"center"}}
            onPress={this._onPressEye.bind(this)}>
          <Image source={this.state.eyeOpened ? require("../../../resource/images/common/eye1.png") : require('../../../resource/images/common/eye.png')}
              style={{width:SizeUtils.translateDesignWidthToCode(33),
            height:SizeUtils.translateDesignWidthToCode(25),}}/>
        </TouchableOpacity>
      </View>
    )
  }

  _onPressEye() {
    this.setState({
      eyeOpened:!this.state.eyeOpened,
    })
  }

  _renderSmsText() {
    return (
      <View style={{flexDirection:"row",
            height:SizeUtils.translateDesignHeightToCode(94),
            borderBottomWidth:SizeUtils.translateFontSizeToCode(3),
            borderColor:"#eeeeee",
            // marginTop:SizeUtils.translateDesignHeightToCode(40),
          }}>
        <TextInput
          style={{
            padding:0,
            width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(54 * 2 + 250),
            height:SizeUtils.translateDesignHeightToCode(94),
            borderWidth: 0,
            textAlignVertical: "center",
            fontSize:SizeUtils.translateFontSizeToCode(32),}}
          onChangeText = {(text) => this._onSmsNumChange(text)}
          placeholder = "验证码"
          underlineColorAndroid="transparent"
          multiline = {false}
          maxLength={6}
          keyboardType="numeric"
          keyboardAppearance="dark"
          value = {this.state.smsNum}
        />
        <TouchableOpacity onPress = {() => this._onRequestSms()} style={{width:SizeUtils.translateDesignWidthToCode(250),
            height:SizeUtils.translateDesignHeightToCode(94), flexDirection:"row", alignItems:"center"}}
          disabled = {this.state.smsIntervalTick > 0}>
          <Text style={[CommonStyles.primaryText, {fontSize:SizeUtils.translateFontSizeToCode(32),
              color:"#000000"}]}>
            {this._getSmsBtnText()}
          </Text>
        </TouchableOpacity>
      </View>
    )
  }

  _getSmsBtnText()  {
    var text = "获取验证码";
    if(this.state.smsIntervalTick > 0) {
      text = text + "(" + this.state.smsIntervalTick + ")";
    }
    return text;
  }

  _onRequestSms() {
    if(this.state.phoneNum == "" || this.state.phoneNum.length != 11) {
      this.setState({
        viewStatus: -901,
      })
    }
    else {
      new RequestSmsAction().call(this, {phoneNum: parseInt(this.state.phoneNum), type:2})
    }
  }

  _renderLoginButton() {
    return(
      <View style={{width:this._width,
          flexDirection:"column", alignItems:"center",
          paddingTop:SizeUtils.translateDesignHeightToCode(180)}}>
        <Button
          backgroundColor="#db3132"
          disabled = {this.state.nickName == "" || this.state.phoneNum == "" ||
            this.state.password == "" || this.state.smsNum == "" ||
            this.state.viewStatus == 4}
          buttonStyle = {{width: this._width,
            height:SizeUtils.translateDesignHeightToCode(80),borderRadius:30}}
          textStyle={{fontSize: SizeUtils.translateFontSizeToCode(30)}}
          title = "完成"
          onPress = {() => this._onPressDoneBtn()}
        />
        <Text style={{color:"#999999", fontSize: SizeUtils.translateFontSizeToCode(24),
          paddingTop: SizeUtils.translateDesignHeightToCode(20)}}>{this._renderSystemNotice()}</Text>
      </View>
    )
  }

  _renderSystemNotice() {
    let statusText = "";
    let showCode = true;
    if(this.state.viewStatus == 1) {
      return "";
    }
    else if(this.state.viewStatus == 2) {
      statusText = "获取验证码中";
      showCode = false;
    }
    else if(this.state.viewStatus == ResponseConstants.status_sms_success) {
      statusText = "验证码已获取";
      showCode = false;
    }
    else if(this.state.viewStatus == 4) {
      statusText = "发送注册请求";
      showCode = false;
    }
    else if(this.state.viewStatus == ResponseConstants.status_phone_length_error) {
      statusText = ResponseConstants.status_phone_length_error_text;
      showCode = false;
    }
    else if(this.state.viewStatus == ResponseConstants.status_nickname_length_error) {
      statusText = ResponseConstants.status_nickname_length_error_text;
      showCode = false;
    }
    else if(this.state.viewStatus == ResponseConstants.status_password_length_error) {
      statusText = ResponseConstants.status_password_length_error_text;
      showCode = false;
    }
    else {
      statusText = this.state.statusText;
    }
    if(showCode) {
      statusText = statusText + " code:" + this.state.viewStatus;
    }
    return statusText;
  }

  _onPressDoneBtn() {
    dismissKeyboard();
    if(this.state.phoneNum == "" || this.state.phoneNum.length != 11) {
      this.setState({
        viewStatus: ResponseConstants.status_phone_length_error,
      })
      return;
    }
    else if(this.strlen(this.state.nickName) < 4){
      this.setState({
        viewStatus: ResponseConstants.status_nickname_length_error,
      })
      return;
    }
    else if(!this.state.password || this.state.password.length < 6) {
      this.setState({
        viewStatus:ResponseConstants.status_password_length_error,
      })
      return;
    }
    new LoginSendRegisteAction().call(this, this.state)
  }

  strlen(str){
    var len = 0;
    for (var i=0; i<str.length; i++) {
     var c = str.charCodeAt(i);
    //单字节加1
     if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
       len++;
     }
     else {
      len+=2;
     }
    }
    return len;
  }
}
